package com.yhsimon.nio.test;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

import static com.yhsimon.nio.c1.ByteBufferUtil.debugAll;

/**
 * @author： YHSimon
 * @date： 2022-07-12 20:37
 */
@Slf4j
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        // 1. 创建固定数量的worker 并初始化
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for(int i=0;i<workers.length;i++){
            workers[i]=new Worker("worker-"+i);
        }
        AtomicInteger index=new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}", sc.getRemoteAddress());
                    //2. 关联 selector
                    log.debug("before register...{}", sc.getRemoteAddress());
                    // round robin 负载均衡算法 轮流分配

                    workers[index.getAndIncrement()%workers.length].register(sc);  // boss线程调用 初始化selector,启动worker-0
                    log.debug("after register...{}", sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false; // 还未初始化

        public Worker(String name) {
            this.name = name;
        }

        // 初始化线程 和 selector
        public void register(SocketChannel sc) throws IOException {// 由于register方法是被boss线程调用的，所以这部分代码都是在boss线程内执行
            if (!start) { //保证代码只执行一遍
                selector = Selector.open();
                thread = new Thread(this, name);
                thread.start(); // 只有worker-0线程启动了，run方法内所有代码才会在worker-0线程内运行
                start = true;
            }

            selector.wakeup(); // 加完任务后 由boss线程唤醒worker-0线程的select方法 防止select方法长时间阻塞
            sc.register(selector, SelectionKey.OP_READ,null);
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();// worker-0  阻塞  wakeup

                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.debug("read...{}", channel.getRemoteAddress());
                            channel.read(buffer);
                            //调试
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
